package mbp.gui.panels;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;

import javax.swing.DefaultListModel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import java.awt.Color;
import javax.swing.JComboBox;
import javax.swing.JButton;
import java.awt.Font;
import javax.swing.JTextField;
import javax.swing.JScrollPane;
import java.awt.Component;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.TimeZone;

import javax.swing.JLabel;
import javax.swing.border.TitledBorder;

import mbp.agents.MbpManagerAgent;
import mbp.base.FeatureType;
import mbp.base.GuiFunction;
import mbp.base.ResourceType;
import mbp.core.Resource;
import mbp.core.ResourceTypeBuilder;
import mbp.exceptions.InvalidFeatureNameException;
import mbp.exceptions.InvalidFeatureTypeException;
import mbp.exceptions.InvalidFeatureValueException;
import mbp.gui.frames.MbpManagerGui;

import javax.swing.UIManager;
import javax.swing.JList;

import org.apache.log4j.Logger;
import javax.swing.JCheckBox;

public class ResourceBuilderGui extends JPanel implements ActionListener
{
	private Resource resource;
	
	private JComboBox cmbResources;
	private JComboBox cmbTypesXml;
	private JButton btnCreateRc;
	private JButton btnDelete;
	private HashMap<String, Resource> resourcesStore;
	//Tablica na zasoby do realizacji uslugi
	private ArrayList<Resource> resourcesSrv; 
	private DefaultListModel modelSrv;// = new DefaultListModel();
	private JTextField txtAgentNameSend;
	private JTextField txtAgentNameGet;
	private JButton btnSend;
	private JButton btnGet;
	private JCheckBox chckbxAll;
	private JLabel lblNewLabel;
	private JLabel lblAgentName;
	private JLabel lblResourcesList;
	private JLabel lblResourceType;
	private int itemCounter;
	
	private MbpManagerAgent myAgent;
	private MbpManagerGui mbpManagerGui;
	
	private ResourceEditPanel panel_4;
	
	private Logger logger = Logger.getLogger(this.getClass());
	//private JButton btnToClient;
	
	
	public ResourceBuilderGui(MbpManagerGui mbpManagerGui) 
	{
		setLayout(null);
		
		myAgent = mbpManagerGui.myAgent;
		this.mbpManagerGui = mbpManagerGui;
		itemCounter = 0;
		
		resourcesStore = new HashMap<String, Resource>();
		resourcesSrv = new ArrayList<Resource>();
		
		JPanel panel_0 = new JPanel();
		panel_0.setLayout(null);
		panel_0.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "Resource Type Fom XML", TitledBorder.LEADING, TitledBorder.TOP, null, new Color(0, 0, 0)));
		panel_0.setBounds(10, 11, 290, 70);
		add(panel_0);
		
		cmbTypesXml = new JComboBox();
		cmbTypesXml.setBounds(10, 39, 125, 20);
		panel_0.add(cmbTypesXml);
		
		btnCreateRc = new JButton("Create");
		btnCreateRc.setName("CREATE");
		btnCreateRc.setFont(new Font("Dialog", Font.PLAIN, 11));
		btnCreateRc.setBounds(145, 36, 90, 23);
		panel_0.add(btnCreateRc);
		
		lblResourceType = new JLabel("Resource type");
		lblResourceType.setBounds(10, 22, 100, 14);
		panel_0.add(lblResourceType);
		
		JPanel panel_1 = new JPanel();
		panel_1.setLayout(null);
		panel_1.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "Active resource", TitledBorder.LEADING, TitledBorder.TOP, null, new Color(0, 0, 0)));
		panel_1.setBounds(10, 92, 290, 70);
		add(panel_1);
		
		cmbResources = new JComboBox();
		cmbResources.setBounds(10, 39, 125, 20);
		panel_1.add(cmbResources);
		
		lblResourcesList = new JLabel("Resources list");
		lblResourcesList.setBounds(10, 24, 110, 14);
		panel_1.add(lblResourcesList);
		
		btnDelete = new JButton("Delete");
		btnDelete.setFont(new Font("Dialog", Font.PLAIN, 11));
		btnDelete.setBounds(145, 38, 90, 23);
		panel_1.add(btnDelete);
		
//		btnToClient = new JButton("->");
//		btnToClient.setFont(new Font("Dialog", Font.PLAIN, 11));
//		btnToClient.setBounds(245, 38, 35, 23);
//		panel_1.add(btnToClient);
//		btnToClient.addActionListener(this);
		
		JPanel panel_2 = new JPanel();
		panel_2.setLayout(null);
		panel_2.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "Send resource", TitledBorder.LEADING, TitledBorder.TOP, null, new Color(0, 0, 0)));
		panel_2.setBounds(10, 173, 290, 70);
		add(panel_2);
		
		txtAgentNameSend = new JTextField();
		txtAgentNameSend.setBounds(10, 39, 125, 20);
		panel_2.add(txtAgentNameSend);
		txtAgentNameSend.setColumns(10);
		
		btnSend = new JButton("Send");
		btnSend.setFont(new Font("Dialog", Font.PLAIN, 11));
		btnSend.setBounds(145, 37, 90, 23);
		panel_2.add(btnSend);
		
		lblNewLabel = new JLabel("Agent name");
		lblNewLabel.setBounds(10, 24, 80, 14);
		panel_2.add(lblNewLabel);
		
		chckbxAll = new JCheckBox("All");
		chckbxAll.setBounds(141, 18, 94, 23);
		panel_2.add(chckbxAll);
		
		JPanel panel_3 = new JPanel();
		panel_3.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "Get resource", TitledBorder.LEADING, TitledBorder.TOP, null, new Color(0, 70, 213)));
		panel_3.setBounds(10, 254, 290, 70);
		add(panel_3);
		panel_3.setLayout(null);
		
		txtAgentNameGet = new JTextField();
		txtAgentNameGet.setBounds(10, 39, 125, 20);
		panel_3.add(txtAgentNameGet);
		txtAgentNameGet.setColumns(10);
		
		btnGet = new JButton("Get");
		btnGet.setFont(new Font("Dialog", Font.PLAIN, 11));
		btnGet.setBounds(145, 38, 90, 23);
		panel_3.add(btnGet);
		
		lblAgentName = new JLabel("Agent name");
		lblAgentName.setBounds(10, 24, 80, 14);
		panel_3.add(lblAgentName);
		
		panel_4 = new ResourceEditPanel(GuiFunction.EDITOR, null);
		panel_4.setBounds(310, 11, 303, 313);
		add(panel_4);
		
		modelSrv = new DefaultListModel();
		
		
		btnCreateRc.addActionListener(this);
		btnDelete.addActionListener(this);
		btnSend.addActionListener(this);
		btnGet.addActionListener(this);
		
		cmbResources.addItemListener(new ItemListener() {
			
			@Override
			public void itemStateChanged(ItemEvent e) 
			{
				
				int index = cmbResources.getSelectedIndex();
				if(index==-1)
				{
					panel_4.clearResourceFields();
					resource = null;
					return;
				}
				String key = (String)cmbResources.getItemAt(index);
				//System.out.println("key: " + key);
				LoadResource(resourcesStore.get(key));
				// TODO Auto-generated method stub
				
			}
		});
		
	}
	
	public void LoadResourceTypeList(List<String> types)
	{
		Iterator<String> it = types.iterator();
		
		while(it.hasNext())
		{
			String type = it.next();
			cmbTypesXml.addItem(type);
		}
	}
	
	public ArrayList getResourcesList()
	{
		//ArrayList<Resource> resourcesList = new ArrayList<Resource>();
		
		//ArrayList<Resource> resourcesList = (ArrayList<Resource>) resourcesStore.
		ArrayList<Resource> resourcesList = new ArrayList<Resource>(resourcesStore.values());
		return resourcesList;
	}

	@Override
	public void actionPerformed(ActionEvent e) 
	{
		if(e.getSource() == btnCreateRc)
		{
			ResourceTypeBuilder rtb = new ResourceTypeBuilder("");
			ResourceType resourceTypeTmp;
			
			resourceTypeTmp = rtb.GetResourceType((String)cmbTypesXml.getSelectedItem());
			Resource resourceTmp = new Resource(resourceTypeTmp);
			
			//Nadanie wartosci domy�lnych dla cech zasobu
			SetDefaultValues(resourceTmp);
			
			AddResource(resourceTmp);
			resource = resourceTmp;
			
			//mbpManagerGui.resourceUtilityGui.CreateUtilityObject(name, resourceType)
			
			return;
		}
		
		if(e.getSource() == btnSend)
		{
			if(chckbxAll.isSelected())
			{
				Iterator<String> it = resourcesStore.keySet().iterator();
				while(it.hasNext())
				{
					String key = it.next();
					myAgent.SendResource(resourcesStore.get(key), txtAgentNameSend.getText());
				}
			}
			else
			{
				myAgent.SendResource(resource, txtAgentNameSend.getText());
			}
			return;
		}
		
		if(e.getSource() == btnGet)
		{
			JOptionPane.showMessageDialog((Component) e.getSource(), "Not implemented yet.", "Warning", JOptionPane.WARNING_MESSAGE);
			return;
		}
		
		if(e.getSource() == btnDelete)
		{
			deleteActiveObject();
			return;
		}
		
//		if(e.getSource() == btnToClient)
//		{
//			if(resource != null)
//			{
//				mbpManagerGui.businessAgentGui.addResource(deleteActiveObject());
//			}
//		}
		
	}
	
	/**
	 * Dodaje nowy zasob do kolekcji zasobow
	 * @param res
	 */
	public void AddResource(Resource res)
	{
		//adding = true;
		//int items = resourcesStore.size();
		String name = res.getType().getResourceTypeName() + " [" + itemCounter++ + "]";
		resourcesStore.put(name, res);
		cmbResources.addItem(name);
		cmbResources.setSelectedItem(name);
		
		LoadResource(resourcesStore.get(name));
		
	}
	
	public Resource deleteActiveObject()
	{
		int index = cmbResources.getSelectedIndex();
		Resource rc = null;
		if(index != -1)
		{
			String key = (String)cmbResources.getItemAt(index);
			rc = resourcesStore.remove(key);
			//cmbResources.removeAllItems();
			cmbResources.removeItemAt(index);
			//cmbResources.validate();
		}
		return rc;
	}
	
	/**
	 * Ustawia domyslne wartosci w polach edycyjnych dla nowo utworzonego zasobu
	 * @param res
	 */
	public void SetDefaultValues(Resource res)
	{
		Iterator it = res.getType().getFeaturesCollection().keySet().iterator();
		while (it.hasNext()) 
		{
			String key = (String)it.next();
			try 
			{
				FeatureType type = res.getFeatureType(key);
				switch(type)
				{
				case INT:
					res.setFeatureValue(key, 0);										
					break;
				case FLOAT:
					res.setFeatureValue(key, Float.parseFloat("0.0"));
					break;
				case ENUM:
					res.setFeatureValue(key, 0);
				default:				
					break;
				}
				
				res.setOwner("WojtekW");
			} 
			catch (InvalidFeatureNameException e) 
			{
				logger.error("InvalidFeatureNameException", e);
			} 
			catch (InvalidFeatureTypeException e) 
			{
				logger.error("InvalidFeatureTypeException", e);
			} 
			catch (InvalidFeatureValueException e) 
			{
				logger.error("InvalidFeatureValueException", e);
			}
			catch (Exception e)
			{
				logger.error("Exception", e);					
			}
			
		}

	}
	
	public void LoadResource(Resource res)
	{
		panel_4.loadResource(res);
		this.resource = res;
		mbpManagerGui.setActiveResource(this.resource);
	}
	
	
	public String DateToFormatedString(Date dt)
	{
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
		df.setTimeZone(TimeZone.getTimeZone("UTC"));
		String dts = df.format(dt);
		return dts;
	}
	
	public Date FormatedStringToDate(String dts) throws ParseException
	{
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
		df.setTimeZone(TimeZone.getTimeZone("UTC"));
		Date dt = df.parse(dts);
		return dt;
	}
}
